import React, { useEffect, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { useNode, useEditor } from '@craftjs/core';
import { DragOutlined, CopyOutlined, DeleteOutlined } from '@ant-design/icons';
import styles from './index.less';

export default ({ render }) => {
  const { id } = useNode();
  const {
    actions,
    query: { createNode, node },
  } = useEditor();

  const {
    dom,
    isHovered,
    isSelected,
    isDisabled,
    connectors: { drag },
  } = useNode((node) => {
    return {
      dom: node.dom,
      isHovered: node.events.hovered,
      isSelected: node.events.selected,
      isDisabled: !!node.data.custom?.disabled,
    };
  });

  // 操作引导样式（样式在global.less文件内）
  useEffect(() => {
    if (dom) {
      dom.classList.add('component-designer-item');
      if (isSelected) {
        dom.classList.add('component-designer-selected');
        dom.classList.remove('component-designer-hovered');
      } else if (isHovered) {
        dom.classList.add('component-designer-hovered');
        dom.classList.remove('component-designer-selected');
      } else {
        dom.classList.remove('component-designer-hovered');
        dom.classList.remove('component-designer-selected');
      }
    }
  }, [dom, isHovered, isSelected]);

  // 获取dom元素在容器内的坐标
  const getPosition = useCallback((domNode) => {
    if (domNode) {
      const { top, left } = domNode.getBoundingClientRect() || {};
      const { top: containerTop, left: containerLeft } =
        document.querySelector('#designer-content')?.getBoundingClientRect() || {};
      const scrollTop = document.querySelector('#designer-content')?.scrollTop || 0;

      return {
        top: `${_.max([top - containerTop + scrollTop, 20])}px`,
        left: `${_.max([left - containerLeft, 0])}px`,
      };
    } else {
      return {
        top: '20px',
        left: '0px',
      };
    }
  }, []);

  return (
    <>
      {id !== 'ROOT' &&
        !isDisabled &&
        isSelected &&
        ReactDOM.createPortal(
          <div
            className={styles.componentControlPopover}
            style={{ left: getPosition(dom).left, top: getPosition(dom).top }}
          >
            <div
              ref={drag}
              title={'移动'}
              style={{ cursor: 'move' }}
              className={styles.componentControlIcon}
            >
              <DragOutlined className={styles.componentControlIconItem} />
            </div>
            <div
              title={'复制'}
              className={styles.componentControlIcon}
              onClick={(e) => {
                e.stopPropagation();
                const {
                  data: { type, props, parent },
                } = node(id).get();
                actions.add(createNode(React.createElement(type, props)), parent || 'ROOT');
              }}
            >
              <CopyOutlined className={styles.componentControlIconItem} />
            </div>
            <div
              title={'删除'}
              className={styles.componentControlIcon}
              onClick={(e) => {
                e.stopPropagation();
                actions.delete(id);
              }}
            >
              <DeleteOutlined className={styles.componentControlIconItem} />
            </div>
          </div>,
          document.querySelector('#designer-content'),
        )}
      {render}
    </>
  );
};
